﻿using AutoMapper;
using ManagementApi.Models;
using ManagementApi.Models.Account;
using ManagementApi.Models.Constructor;
using ManagementApi.Mvc;
using ManagementApi.Mvc.ApplicationContexts;
using ManagementApi.Mvc.Authorization;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Modules.Constructor;
using Modules.System.Area;
using Modules.System.Security;
using Modules.System.User;
using PmSoft;
using PmSoft.Entity;
using PmSoft.Utilities;
using System.ComponentModel.DataAnnotations;

namespace ManagementApi.Controllers.AdminPannel
{
    /// <summary>
    /// 建设单位管理
    /// </summary>
    [Route("/api/v1/sysuser/Constructor")]
    [ApiController]
    [Authorize(Roles = "SysUser")]
    public class ConstructorController : ControllerBase
    {
        private readonly ConstructorService constructorService;
        private readonly AreaService areaService;
        private IMapper mapper;
        private ManagementApplicationContext applicationContext;
        private readonly SecurityService securityService;

        public ConstructorController(AreaService areaService, ConstructorService constructorService, IMapper mapper, ManagementApplicationContext applicationContext, SecurityService securityService)
        {
            this.constructorService = constructorService;
            this.mapper = mapper;
            this.areaService = areaService;
            this.applicationContext = applicationContext;
            this.securityService = securityService;
        }

        /// <summary>
        /// 建设单位分页
        /// </summary>
        /// <param name="query"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet("page")]
        public ApiResult<PageDto<ConstructorDto>> GetConstructors([FromQuery] ConstructorQuery query, int pageIndex = 1, int pageSize = 9999)
        {
            var data = constructorService.GetConstructors(query, pageIndex, pageSize);
            var dtos = data.AsPageDto(source => { return source.AsDto(); });
            return ApiResult<PageDto<ConstructorDto>>.Success(dtos);
        }

        /// <summary>
        /// 建设单位详情
        /// </summary>
        /// <param name="constructorId"></param>
        /// <returns></returns>
        [HttpGet("{constructorId}/form")]
        public ApiResult<ConstructorCreateForm> GetConstructor(int constructorId)
        {
            var data = constructorService.GetConstructorInfo(constructorId);
            if (data == null)
                return ApiResult<ConstructorCreateForm>.Failure("建设单位数据不存在");
            ConstructorCreateForm form = new ConstructorCreateForm();
            mapper.Map(data, form);
            form.TypeName = form.Type?.GetDescription();
            form.AreaName = areaService.GetAreaFullName(form.ProvinceCode, form.CityCode, form.AreaCode);
            return ApiResult<ConstructorCreateForm>.Success(form);
        }

        /// <summary>
        /// 修改建设单位信息
        /// </summary>
        /// <param name="id"></param>
        /// <param name="from"></param>
        /// <returns></returns>
        [HttpPut("{id}")]
        [PermissionCheck("corp:constructorinfo:edit")]
        public ApiResult Update(int id, [FromBody] ConstructorCreateForm from)
        {
            ConstructorInfo? data = constructorService.GetConstructorInfo(id);
            if (data == null)
                return ApiResult.Failure("建设单位数据不存在");
            mapper.Map(from, data);
            constructorService.Update(data);
            return ApiResult.Success("修改成功");
        }

        /// <summary>
        /// 删除建设单位信息
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpDelete("{ids}")]
        [PermissionCheck("corp:constructorinfo:delete")]
        public ApiResult Deleted(string ids)
        {
            constructorService.Deletes(ValueUtility.ConvertToList<int>(ids));
            return ApiResult.Success("删除成功");
        }

        /// <summary>
        /// 重置密码
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPut("resetPassword/{id}")]
        [PermissionCheck("corp:constructorinfo:resetpassword")]
        public ApiResult EditPassWord(int id, [Required(ErrorMessage = "密码不能为空")] string passWord)
        {
            ConstructorInfo? data = constructorService.GetConstructorInfo(id);
            if (data == null)
                return ApiResult.Failure("建设单位数据不存在");
            SysSecurity? sysSecurity = securityService.GetSysSecurity(data.SecurityId);
            if (sysSecurity != null)
            {
                sysSecurity.Password = SecurityPasswordHelper.EncodePassword(passWord, UserPasswordFormat.SM4);
                securityService.Update(sysSecurity);
            }
            else
            {
                sysSecurity = new()
                {
                    Password = SecurityPasswordHelper.EncodePassword(passWord, UserPasswordFormat.SM4),
                    UserType = UserType.Constructor,
                    IsAuth = false
                };
                securityService.Create(sysSecurity);
            }
            return ApiResult.Success("密码重置成功");
        }
    }
}